<template>
  <div class="page-container">
    <!--工具栏-->
    <div class="toolbar">
      <el-form :inline="true" :model="filters" :size="size">
        <el-row class="search-input pb0">
          <el-form-item label="客服帐号：">
            <el-input v-model="filters.account" clearable placeholder="客服账号"></el-input>
          </el-form-item>
          <el-form-item label="客服昵称：">
            <el-input v-model="filters.nickName" clearable placeholder="客服昵称"></el-input>
          </el-form-item>
          <el-form-item label="状态：">
            <el-select v-model="filters.status"  placeholder="状态">
              <el-option label="启用" value="1"></el-option>
              <el-option label="禁用" value="0"></el-option>
            </el-select>
          </el-form-item>
          <el-row class="search-button button">
            <el-form-item>
              <kt-button
                icon="fa fa-search"
                :label="$t('action.search')"
                type="primary"
                @click="findPage(null)"
              />
            </el-form-item>
            <el-form-item>
              <kt-button
                icon="fa fa-plus"
                :label="$t('action.add')"
                type="primary"
                @click="handleAdd"
              />
            </el-form-item>
            <el-form-item>
              <kt-button
                icon="fa fa-refresh"
                :label="$t('action.reset')"
                type="primary"
                @click="resetForm('filters')"
              />
            </el-form-item>
            <el-form-item>
              <kt-button label="启用/停用" type="primary" @click="editStatus" />
            </el-form-item>
          </el-row>
        </el-row>
        <!-- <el-row class="search-button">
          <el-form-item>
            <kt-button
              icon="fa fa-search"
              :label="$t('action.search')"
              type="primary"
              @click="findPage(null)"
            />
          </el-form-item>
          <el-form-item>
            <kt-button
              icon="fa fa-plus"
              :label="$t('action.add')"
              type="primary"
              @click="handleAdd"
            />
          </el-form-item>
          <el-form-item>
            <kt-button
              icon="fa fa-hand-pointer-o"
              :label="$t('action.reset')"
              type="primary"
              @click="resetForm('filters')"
            />
          </el-form-item>
        </el-row>-->
        <el-form-item class="t_r w100">
          <el-button-group>
            <el-tooltip content="刷新" placement="top">
              <el-button icon="fa fa-refresh" @click="findPage(null)"></el-button>
            </el-tooltip>
            <el-tooltip content="列显示" placement="top">
              <el-button icon="fa fa-filter" @click="displayFilterColumnsDialog"></el-button>
            </el-tooltip>
            <el-tooltip content="导出" placement="top">
              <el-button icon="fa fa-file-excel-o" @click="downloadExcel" id="downloadExcel"></el-button>
            </el-tooltip>
          </el-button-group>
        </el-form-item>
        <!--表格显示列界面-->
        <table-column-filter-dialog
          ref="tableColumnFilterDialog"
          :columns="columns"
          @handleFilterColumns="handleFilterColumns"
        ></table-column-filter-dialog>
      </el-form>
    </div>
    <!--表格内容栏-->
    <Jic-table
      :height="350"
      :tableList="pageResult"
      :tableHeaderList="filterColumns"
      @findPage="findPage"
      :showBatchDelete="false"
      :showEditOperation="true"
      :showDeleteOperation="true"
      @handleDelete="handleDelete"
      :totalSize="totalSize"
      @handleEdit="handleEdit"
      @handlePageChange="handlePageChange"
      @handleDetail="handleDetail"
      @selectionChange="selectionChange"
      ref="JicTable"
    ></Jic-table>
    <!--新增编辑界面-->
    <el-dialog
      :title="operation"
      width="40%"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
    >
      <el-form
        :model="dataForm"
        :disabled =isdisabled
        label-width="120px"
        :rules="dataFormRules"
        ref="dataForm"
        :size="size"
        label-position="right"
      >
        <el-row class="searchDialog-input">
          <el-form-item label="客服昵称：" prop="nickName">
          <el-input v-model="dataForm.nickName" auto-complete="off" clearable placeholder="请输入客服昵称"></el-input>
        </el-form-item>
        <el-form-item label="客服账号：" prop="account">
          <el-input v-model="dataForm.account" auto-complete="off" clearable placeholder="请输入客服账号"></el-input>
        </el-form-item>
        <el-form-item label="客服标题：" prop="title">
          <el-input v-model="dataForm.title" auto-complete="off" clearable placeholder="请输入客服标题"></el-input>
        </el-form-item>
        <el-form-item label="生效终端：" prop="effectiveTerminal">
          <el-select v-model="dataForm.effectiveTerminal" clearable placeholder="请输入生效终端" style="width: 100%">
            <el-option label="PC" :value="0"></el-option>
            <el-option label="APP" :value="1"></el-option>
            <el-option label="移动端" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="启用开关：" prop="status">
          <el-select v-model="dataForm.status" clearable placeholder="请输入启用开关" style="width: 100%">
            <el-option label="启用" :value="1"></el-option>
            <el-option label="禁用" :value="0"></el-option>
          </el-select>
        </el-form-item>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button :size="size" @click.native="dialogVisible = false">{{$t('action.cancel')}}</el-button>
        <el-button
          :loading="editLoading"
          :size="size"
          type="primary"
          @click.native="submitForm"
          :style="{ display: submitShow }"
        >{{$t('action.submit')}}</el-button>
      </div>

    </el-dialog>
  </div>
</template>

<script>
import PopupTreeInput from "@/components/PopupTreeInput";
// import JicTable from "@/components/jicComponentGallery/jicTable";
import JicTable from "@/views/Core/CustomerServiceTable";
import KtButton from "@/views/Core/KtButton";
import TableColumnFilterDialog from "@/views/Core/TableColumnFilterDialog";
import { format } from "@/utils/datetime";
import { exportExcel } from "@/utils/excel";
export default {
  components: {
    PopupTreeInput,
    JicTable,
    KtButton,
    TableColumnFilterDialog
  },
  data() {
    return {
      totalSize: 0,
      size: "small",
      filters: {
        account: "",
        nickName: "",
        status: ""
      },
      columns: [],
      filterColumns: [],
      pageRequest: { pageNum: 1, pageSize: 10 },
      pageResult: [],
      options: {},
      operation: '编辑', // true:新增, false:编辑
      dialogVisible: false, // 新增编辑界面是否显示
      isdisabled : false,
      editLoading: false,
      //提交按键隐藏
      submitShow: "",
      dataFormRules: {
        nickName: [{ required: true, message: "请输入客服昵称", trigger: "blur" }],
        account: [
          { required: true, message: "请输入客服账号", trigger: "blur" },
          {pattern:"^\w{3,20}$", message: '仅可输入数字、26个英文字母或者下划线', trigger: 'blur'},
        ],
        title: [{ required: true, message: "请输入客服标题", trigger: "blur" }],
        effectiveTerminal: [
          { required: true, message: "请选择生效终端", trigger: "blur" }
        ],
        status: [{ required: true, message: "请选择是否禁用", trigger: "blur" }]
      },

      // 新增编辑界面数据
      dataForm: {
        nickName: "",
        account: "",
        title: "",
        effectiveTerminal: " ",
        status: ""
      },

      //选中ID Array
      idArray: []
    };
  },
  methods: {
    // 获取分页数据
    findPage: function(data) {
      if (data != null && data.start != null) {
        if (data.start != null) {
          this.pageRequest.pageNum = data.start;
        }
        if (data.limit != null) {
          this.pageRequest.pageSize = data.limit;
        }
      }

      let this_ = this;
      if (this_.filters == undefined || this_.filters == null) {
        this_.filters = {};
      }
      this_.filters.start = this.pageRequest.pageNum;
      this_.filters.limit = this.pageRequest.pageSize;
      this_.utils.request.queryCustomerService(this_.filters, function(res) {
        this_.pageResult = res.data.rows;
        this_.totalSize = Number(res.data.total);
      });
    },

    //左右分页点击
    handlePageChange(params) {
      if (params != null && params.number != null) {
        if (params.number != null) {
          this.pageRequest.pageNum = params.number;
        }

        this.findPage();
      }
    },
    //数据勾选
    selectionChange(data) {
      console.log(data);
      this.idArray = data.selections;
    },
    // 删除
    handleDelete: function(data) {
      console.log(data, "-----");
      this.$confirm("确认删除吗？", "提示", {}).then(() => {
        var params = {};
        params.id = data.row.id;

        var this_ = this;
        this.utils.request.deleteCustomerService(params, function(res) {
          if (res.code == "0000") {
            this_.$message({ message: "操作成功", type: "success" });
            this_.findPage(null);
          } else {
            this_.$message({
              message: "操作失败, " + res.msg,
              type: "error"
            });
          }
        });
      });
    },
    // 详情页面
    handleDetail(params) {
      this.isdisabled = true;
      if (this.$refs["dataForm"]) {
        this.$refs["dataForm"].clearValidate();
      }
      if (params.row.id != null) {
        this.statusShow = false;
      }
      this.dialogVisible = true;
      this.operation = '详情';
      this.submitShow = 'none';
      this.dataForm = Object.assign({}, params.row);
    },
    // 显示新增界面
    handleAdd: function() {
      this.isdisabled = false;
      this.submitShow = "";
      this.dialogVisible = true;
      this.operation = '新增';
      this.dataForm = {};
    },
    //列表下载
    downloadExcel() {
      this.$confirm("确定下载列表文件?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let this_ = this;
          this.utils.request.queryCustomerService(this_.filters, function(res) {
            exportExcel(res.data.rows, this_.filterColumns, "客服管理");
          });
        })
        .catch(() => {});
    },

    // 显示编辑界面
    handleEdit: function(params) {
      this.isdisabled = false;
      this.submitShow = "";
      this.dialogVisible = true;
      this.operation = '编辑';
      this.operation = false;
      this.dataForm = Object.assign({}, params.row);
    },
    // 编辑
    submitForm: function() {
      this.$refs.dataForm.validate(valid => {
        if (valid) {
          let params = Object.assign({}, this.dataForm);
          let this_ = this;
          params.token = localStorage.getItem("token");
          this.utils.request.editCustomerService(params, function(res) {
            if (res.code == "0000") {
              this_.$message({ message: "操作成功", type: "success" });

              this_.$refs["dataForm"].resetFields();

              this_.dialogVisible = false;

              this_.findPage(null);
            } else {
              this_.$message({
                message: "操作失败, " + res.msg,
                type: "error"
              });
            }
          });
        }
      });
    },
    //启用停用
    editStatus: function() {
      if (this.idArray.length != 1) {
        this.$message({
          message: "请选择一条数据进行处理, ",
          type: "error",
          center: true,
          offset: 250,
          duration: 1000
        });
      } else {
        let params = {};
        params.id = this.idArray[0].id;
        if (this.idArray[0].status == "0") {
          params.status = "1";
        } else if (this.idArray[0].status == "1") {
          params.status = "0";
        }
        var this_ = this;
        this.utils.request.editCustomerService(params, function(res) {
          this_.$message({
            message: "操作成功",
            type: "success",
            center: true,
            offset: 250,
            duration: 1000
          });
          this_.findPage(null);
        });
      }
    },
    // 时间格式化
    dateFormat: function(row, column, cellValue, index) {
      return format(row[column.property]);
    },
    // 处理表格列过滤显示
    displayFilterColumnsDialog: function() {
      this.$refs.tableColumnFilterDialog.setDialogVisible(true);
    },
    // 处理表格列过滤显示
    handleFilterColumns: function(data) {
      this.filterColumns = data.filterColumns;
      this.$refs.tableColumnFilterDialog.setDialogVisible(false);
    },
    // 处理表格列过滤显示
    initColumns: function() {
      this.columns = [
        { prop: "nickName", label: "客服昵称", minWidth: 50 },
        { prop: "account", label: "客服账号", minWidth: 120 },
        { prop: "title", label: "客服标题", minWidth: 120 },
        {
          prop: "effectiveTerminal",
          label: "生效终端",
          minWidth: 120,
          formatter: function(row, column, cellValue, index) {
            if (cellValue == 0) {
              return "PC";
            } else if (cellValue == 1) {
              return "APP";
            } else if (cellValue == 2) {
              return "移动端";
            }
          }
        },
        {
          prop: "status",
          label: "是否禁用",
          minWidth: 120,
          formatter: function(row, column, cellValue, index) {
            if (cellValue == 0) {
              return "禁用";
            } else if (cellValue == 1) {
              return "启用";
            }
          }
        },
        { prop: "createTime", label: "创建时间", minWidth: 120 }
        // {prop:"lastUpdateTime", label:"更新时间", minWidth:120, formatter:this.dateFormat}
      ];
      var temp = [];
      $.each(this.columns, function(key, val) {
        temp.push(val);
      });
      this.filterColumns = temp;
    },
    resetForm(formName) {
      this.filters = {
        name: "",
        number: "",
        title: "",
        effectiveTerminal: "",
        status: ""
      };
      this.findPage();
    }
  },

  mounted() {
    this.initColumns();
    this.findPage();
  }
};
</script>

<style lang='scss' scoped>
.button {
  /deep/ .el-form-item {
    margin-bottom: 20px !important;
    margin-top: 10px;
  }
}
.pb0 {
  padding-bottom: 0px;
}
.search-button {
  .el-form-item {
    margin-right: 0px !important;
  }
}
.mr30 {
  margin-right: 30px;
}
</style>
